<?php


namespace App\Api\Hmyl;
use PhalApi\Api;
use PhalApi\Exception\BadRequestException;

/**
 * 韩美医疗yuyue
 *
 * @author: dogstar <chanzonghuang@gmail.com> 2014-10-04
 */
class Xiadan extends Api
{

    public function getRules()
    {
        return array(
            'yuyue' => array(),
        );
    }


    /**
     * yuyue
     */

    public function yuyue()
    {
        $frdm = 'A003918';
        $url = 'https://26er314622.goho.co/?s=App.Zhjl.getOrderHeaderAdd';


        $item = \PhalApi\DI()->notorm->zhjlgetworklist->where(  array( 'todo' => '0', "sync" => '1' ) )->fetchOne();


        if (!$item) {
            throw new BadRequestException('没有需要下单的订单');
        }

        $taskId = $item['taskId'];

        $items = \PhalApi\DI()->notorm->zhjlgetworklist->where(  array( 'taskId' => $taskId ) )->fetchAll();

        $itemNos = array_map(function ($item) {
            return $item['itemNo'];
        }, $items);




        // 先实例
        $curl = new \PhalApi\CUrl();

        $itemNolist = array();

        foreach ($itemNos as $itemNo) {
            $data = array(
                'page' => 1,
                'size' => 99,
                'username' => $frdm,
                'where' => json_encode(array(
                        "management_number" => $itemNo,
                    )) 
            );
            $url = 'https://26er314622.goho.co/?s=App.Zhjlsb.Getsb';
            $rs = $curl->post($url, $data , 3000);
            $arr = json_decode($rs, true);
            $itemNolist[] = $arr['data']['data'][0];
            // return $arr['data']['data'][0];
        }

        // return $itemNolist;

        $curl->setHeader(array('Content-Type' => 'application/json'));
        $data = array(
            'frdm' => $frdm,
        );
        $url = 'https://26er314622.goho.co/?s=App.Zhjl.getOrderHeaderAdd';
        $rs = $curl->post($url, json_encode($data), 3000);
        $headerInfo = json_decode($rs, true)['data'][0];
        $headerInfo['service_type'] = '送检';
        $headerInfo['zdrq'] = $item['planDate'];
        $headerInfo['bz'] = $headerInfo['bz'] . '【' . $taskId . '】';

        $postData = array(
            'headerInfo' => json_encode($headerInfo),
            'tables' => json_encode($itemNolist),
        );

        // return $postData;
        $curl->setHeader(array('Content-Type' => 'application/json'));
        $url = 'https://26er314622.goho.co/?s=App.ZhjlOrderSave.saveBH';
        $rs = $curl->post($url, json_encode($postData), 1000*60*5);

        // return $rs;

        $rs = json_decode($rs, true);

        if ($rs['code'] == 200) {
            $item_zhjl = \PhalApi\DI()->notorm->zhjlgetworklist->where(  array( 'taskId' => $taskId ) )->update( array( 'todo' => '1' , 'dh' => $rs['data'][4]['dh'] ) );
        }

        return $rs;
    }


    
}
